package deployr.core;

import java.util.*;

import deployr.domain.*;
import static java.text.MessageFormat.*;

public class ProjectBuilder {

	private final Workspace workspace;

	private final Projects projects;

	public ProjectBuilder(Workspace workspace) {
		this.workspace = workspace;
		this.projects = new Projects();
		projects.saveOn(workspace);
	}

	public ProjectBuilder scan() {
		List<Metadata> someMetadata = workspace.projectsMetadata();
		for (Metadata metadata : someMetadata) {
			addProject(metadata, scanUpdates(metadata));
		}
		return this;
	}

	private List<IUpdate> scanUpdates(Metadata metadata) {
		return new UpdateBuilder(workspace).scan(metadata.get("path")).getUpdates();
	}

	private void addProject(Metadata metadata, List<IUpdate> updates) {
		Project project = new Project(metadata, updates);
		project.saveOn(workspace);
		project.updateChecksum(workspace.checksum(project.getPath()));
		log("found project {0}", project.getPath());
		projects.addProject(project);
	}

	private void log(String string, String... args) {
		System.out.println(format(string, args));
	}

	public Projects getProjects() {
		return projects;
	}

}